import pymysql
import time
import sys
# 尝试导入系统通知库
notification = None
notification_type = ""  # 当前使用的通知库类型 (plyer/win10toast)

try:
    from plyer import notification
    notification_type = "plyer"
except ImportError:
    pass

try:
    if notification is None:
        from win10toast import ToastNotifier
        notification = ToastNotifier()
        notification_type = "win10toast"
except ImportError:
    pass
from threading import Thread

"""
    安全打印函数，处理中文编码问题
    :param message: 要打印的消息
"""
def safe_print(message):
    try:
        print(message)
    except UnicodeEncodeError:
        # 处理控制台编码不支持中文的情况
        encoded = str(message).encode('utf-8', errors='replace')
        print(encoded.decode(sys.stdout.encoding, errors='replace'))

"""
    发送系统通知
    :param title: 通知标题
    :param message: 通知内容
"""
def show_notification(title, message):
    safe_print(f"尝试发送通知: {notification_type}")
    try:
        if notification_type == "plyer":
            notification.notify(
                title=title,
                message=message,
                app_name="MySQL监控工具",
                timeout=10
            )
        elif notification_type == "win10toast":
            notification.show_toast(
                title=title,
                msg=message,
                duration=10,
                threaded=True
            )
        else:
            safe_print("未找到通知库，请安装plyer或win10toast")
            return
        safe_print("通知发送成功")
    except Exception as e:
        safe_print(f"通知发送失败: {str(e)}")

# 初始化时显示通知库状态
if notification_type:
    safe_print(f"通知系统初始化成功: {notification_type}")
else:
    safe_print("警告: 未找到可用的通知库，将无法显示弹窗通知")

"""
    MySQL表实时监控主函数
    连接数据库并定期检查新数据变化
"""
def monitor_mysql():
    # 获取用户输入的要监控的表名
    table_input = input("请输入要监控的表名，多个表用逗号分隔: ")
    monitored_tables = [table.strip() for table in table_input.split(',') if table.strip()]

    if not monitored_tables:
        safe_print("错误: 未输入任何表名，程序将退出")
        return

    safe_print(f"将监控以下表: {', '.join(monitored_tables)}")

    # 数据库连接配置 - 必须修改为实际环境信息
    config = {
        'host': '服务器IP',       # MySQL服务器地址
        'port': 3306,            # MySQL端口号
        'user': '用户名',        # 数据库登录用户名
        'password': '密码',      # 数据库登录密码
        'db': '数据库名',        # 要监控的数据库名称
        'charset': 'utf8mb4'     # 字符集设置
    }

    # 为每个表维护独立的最后ID记录
    table_last_ids = {table: 0 for table in monitored_tables}  # 字典：键-表名，值-最后ID

    # 常量定义 - 可根据需求调整
    CHECK_INTERVAL = 60  # 监控检查间隔(秒)

    # 初始化每个表的最后ID
    try:
        conn = pymysql.connect(**config)
        safe_print(f"数据库连接成功: {config['host']}:{config['port']}/{config['db']}")
        with conn.cursor() as cursor:
            for table in monitored_tables:
                cursor.execute(f"SELECT MAX(id) FROM {table}")
                result = cursor.fetchone()  # 获取查询结果 (最大ID值)
                table_last_ids[table] = result[0] or 0
                safe_print(f"表 {table} 初始化成功，当前最大ID: {table_last_ids[table]}")
        conn.close()
    except Exception as e:
        safe_print(f"初始化错误: {e}")

    while True:
        try:
            conn = pymysql.connect(**config)
            with conn.cursor() as cursor:
                # 查询大于上次记录ID的新数据
                # 循环检查每个表的新数据
                for table in monitored_tables:
                    try:
                        # 查询大于上次记录ID的新数据
                        cursor.execute(f"SELECT * FROM {table} WHERE id > %s ORDER BY id ASC", (table_last_ids[table],))
                        new_rows = cursor.fetchall()  # 获取所有新增记录

                        if new_rows:
                            safe_print(f"表 {table} 查询到 {len(new_rows)} 条新数据")
                            for row in new_rows:
                                table_last_ids[table] = row[0]  # 更新最后ID
                                safe_print(f"表 {table} 检测到新数据，ID: {row[0]}")
                                try:
                                    show_notification(
                                        f"MySQL表 {table} 新数据",
                                        f"ID: {row[0]}\n内容: {str(row)[:100]}..."
                                    )
                                    safe_print(f"表 {table} 通知已发送")
                                except Exception as e:
                                    safe_print(f"表 {table} 通知发送失败: {e}")
                        else:
                            safe_print(f"表 {table} 无新数据")
                    except Exception as e:
                        safe_print(f"表 {table} 查询错误: {e}")

            conn.close()
        except Exception as e:
            safe_print(f"监控错误: {e}")

        # 检查间隔时间(秒) - 可根据实际需求调整
        CHECK_INTERVAL = 120  # 常量：监控检查间隔，单位秒
        time.sleep(CHECK_INTERVAL)

if __name__ == "__main__":
    # 创建监控线程，设置为守护线程
    monitor_thread = Thread(target=monitor_mysql, daemon=True)
    monitor_thread.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("监控停止")
